package deng.jbservice.examples.jpa;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;

@Stateless
@Local(JpaQueryRunner.class)
@WebService
public class JpaQueryRunnerBean implements JpaQueryRunner {

	private Logger logger = Logger.getLogger(JpaQueryRunnerBean.class);
	
	@PersistenceContext(unitName="jpa-examples")
	private EntityManager entityManager;
	
	@WebMethod
	@Override
	public String executeQuery(String query) {
		List<?> resultList = entityManager.createQuery(query).getResultList();
		StringBuilder out = new StringBuilder();
		out.append("<resultList>");
		for (Object object : resultList) {			
			String result = ToStringBuilder.reflectionToString(object, ToStringStyle.DEFAULT_STYLE, false, object.getClass());
			logger.info("<result>" + result + "</result>");
			out.append(object);
		}
		out.append("</resultList>");
		return out.toString();
	}

}
